//
//  ExeSql.js
//  SugLisSystem
//	执行sql的方法的简化
//  Created by MrRight on 2012-11-21.
//  Copyright 2012 MrRight. All rights reserved.
//
var DATABASE_NAME = 'sls';
var pubFun = require('untils/PubFun');

/**返回数据类型为array*/
var TYPE_ARRAY = 0;
exports.TYPE_ARRAY = TYPE_ARRAY;
/**返回数据类型为object*/
var TYPE_OBJECT = 1;
exports.TYPE_OBJECT = TYPE_OBJECT;

/**
 * 执行指定sql语句的静态方法
 * @param sql 需要执行的sql
 * @param type 返回数据类型
 * */function execSQL(sql, type) {
	var db = Ti.Database.open(DATABASE_NAME);
	var result = null;
	var resultSet = [];
	try {
		result = db.execute(sql);
	} catch(e) {
		Ti.API.error('[EXESQL]执行查询SQL：' + sql + "出错！")
		db.close();
		return resultSet;
	}
	if (pubFun.isNull(type) || type == TYPE_ARRAY) {
		resultSet = getArrayRuslut(result);
	} else if (type == TYPE_OBJECT) {
		resultSet = getObjectRuslut(result);
	} else {
		Ti.API.error("[EXESQL]No Such Method:" + type);
	}
	if (result != null) {
		result.close();
	}
	db.close();
	return resultSet;
}

exports.execSQL = execSQL;
/**获取array型数据*/
function getArrayRuslut(result) {
	var arrayReslut = [];
	while (result != null && result.isValidRow()) {
		sigleReslut = [];
		for (var i = 0; i < result.fieldCount(); i++) {
			sigleReslut.push(result.field(i));
		}
		arrayReslut.push(sigleReslut);
		result.next();
	}
	return arrayReslut;
}

/**获取object型数据*/
function getObjectRuslut(result) {
	var arrayReslut = [];
	while (result != null && result.isValidRow()) {
		sigleReslut = {};
		for (var i = 0; i < result.fieldCount(); i++) {
			sigleReslut[result.fieldName(i).toLowerCase()] = result.field(i);
		}
		arrayReslut.push(sigleReslut);
		result.next();
	}
	return arrayReslut;
}

exports.execUpdateSQL = function(sql) {
	var db = Ti.Database.open(DATABASE_NAME);
	try {
		db.execute(sql);
	} catch(e) {
		Ti.API.error('[EXESQL]执行更新SQL：' + sql + "出错！")
		db.close();
		return false;
	}
	return true;
}

exports.getOneValue = function(sql) {
	var reslutSet = execSQL(sql);
	if (reslutSet.length > 0 && reslutSet[0].length > 0) {
		return reslutSet[0][0];
	} else {
		return null;
	}
}

